package Collections集合工具类;

import javax.rmi.CORBA.Stub;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Collections集合工具类案例 {
    public static void main(String[] args) {
        /*创建ArrayList集合对象*/
        ArrayList<Srudent> arrayList = new ArrayList<>();
        /*创建学生对象*/
        Srudent s1 = new Srudent("linqinxai", 30);
        Srudent s2 = new Srudent("zahngmanyu", 30);
        Srudent s3 = new Srudent("wangzuxain", 30);
        Srudent s4 = new Srudent("liuyan", 30);
        /*把学生添加到集合*/
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        arrayList.add(s4);
        /*使用Collections对ArrayList集合排序*/
        /*sort(List<T> list,Comparator<? super T> c)*/
        Collections.sort(arrayList, new Comparator<Srudent>() {
            @Override
            public int compare(Srudent s1, Srudent s2) {
                /*按照年龄的从小到大排序，年龄相同时，按照姓名的字母顺序排序*/
                int num=s1.getAge()-s2.getAge();
                int num2=num==0?s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });
        /*遍历集合*/
        for (Srudent s:arrayList) {
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}
/*
* 学生类
* */
class Srudent{
    private String name;
    private int age;

    public Srudent() {
    }

    public Srudent(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}